/*******************************************************************************
 *
 *    Copyright (c) Baina Info Tech Co. Ltd
 *
 *    Best Flash Light HD_Investigate
 *    
 *    RatingDialogHelper
 *    TODO File description or class description.
 *
 *    @author: zuochen
 *    @since:  2011-10-28
 *    @version: 1.0
 *
 ******************************************************************************/

package com.sdk.markting.util;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.widget.Toast;

/**
 * RatingDialogHelper of Best Flash Light HD_Investigate.
 * 
 * @author zuochen
 * 
 */

public class RatingDialogHelper {
	static Context mContext;
	private static RatingDialogHelper mRatingDialogHelper;

	public static RatingDialogHelper getInstance(Context context) {
		mContext = context;
		if (null == mRatingDialogHelper) {
			mRatingDialogHelper = new RatingDialogHelper();
		}
		return mRatingDialogHelper;
	}

	public void ratingApp() {
		if (Rating.getInstance(mContext).isShouldShowRating()) {
			showRateDialog();
		}
	}

	private void showRateDialog() {

		new AlertDialog.Builder(mContext)
				.setTitle("Rate me in market")
				.setMessage(
						"Dear users, If you like our app, please give us 5 stars. Your sustained support is the source of our improvement.")
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Rating.getInstance(mContext).saveIsHasRated();
						doRating(mContext.getPackageName());
					}
				}).setNegativeButton("Cancel", null).create().show();
	}

	public static final String MARKET_PACKAGE_NAME = "com.android.vending";

	public void doRating(String packageName) {
		if (!isPackageInstalled(mContext, MARKET_PACKAGE_NAME)) {
			Toast.makeText(mContext, "Can't find Google Market Client.",
					Toast.LENGTH_SHORT).show();
			return;
		}
		final Uri marketUri = Uri.parse("market://details?id=" + packageName);
		final Intent intent = new Intent(Intent.ACTION_VIEW, marketUri);
		intent.addCategory(Intent.CATEGORY_BROWSABLE);
		mContext.startActivity(intent);
	}

	public static boolean isPackageInstalled(Context context, String packageName) {
		boolean r = false;
		final PackageManager pm = context.getPackageManager();
		try {
			final PackageInfo packageInfo = pm.getPackageInfo(packageName, 0);
			if (packageInfo != null) {
				r = true;
			}
		} catch (final NameNotFoundException e) {
		}
		return r;
	}
}
